package oen.game.assist.kit.util;

import boofcv.alg.template.TemplateMatching;
import boofcv.factory.template.FactoryTemplateMatching;
import boofcv.factory.template.TemplateScoreType;
import boofcv.io.image.ConvertBufferedImage;
import boofcv.struct.feature.Match;
import boofcv.struct.image.GrayF32;
import im.oen.boot.common.data.Point;
import im.oen.boot.common.utils.Checker;

import java.awt.image.BufferedImage;
import java.util.Comparator;
import java.util.List;

/**
 * <p>描述：暂无描述信息</p>
 *
 * <p>创建时间：2021-12-18 16:54</p>
 * <p>更新时间：暂无</p>
 *
 * @author Kevin.Xu
 * @version 1.0
 */
public class ImageDetect {

    /**
     * 在图片中定位截图
     *
     * @param screenImage     全局图片
     * @param screenshotImage 需要在全局中定位的图片截图
     * @return
     */
    public static Point position(BufferedImage screenImage, BufferedImage screenshotImage) {
        GrayF32 screen = ConvertBufferedImage.convertFromSingle(screenImage, null, GrayF32.class);
        GrayF32 box = ConvertBufferedImage.convertFromSingle(screenshotImage, null, GrayF32.class);
        TemplateMatching<GrayF32> matcher = FactoryTemplateMatching.createMatcher(TemplateScoreType.SUM_SQUARE_ERROR, GrayF32.class);
        matcher.setImage(screen);
        matcher.setTemplate(box, null, 4);
        matcher.process();
        List<Match> found = matcher.getResults().toList();
        if (Checker.isEmpty(found)) {
            return null;
        }
        Match bestMatch = found.stream().max(Comparator.comparing(m -> m.score)).get();
        if (bestMatch == null) {
            return null;
        }
        return Point.of(bestMatch.x, bestMatch.y);
    }
}
